﻿using Cookbook.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Windows.Web.Http;
using Windows.Networking.Connectivity;
using Windows.Storage;
using Windows.Networking.BackgroundTransfer;
using SQLite;

namespace Cookbook.Services
{
  public class RecipeService
  {
    private static string RECIPE_BASEURL = "http://localhost:54321/api/Recipes";

    public async static Task<IList<Recipe>> GetRecipes()
    {
      IList<Recipe> recipes;

      bool hasConnection = NetworkInformation.GetInternetConnectionProfile() == null;

      if (hasConnection)
      {
        var url = new Uri(RECIPE_BASEURL);
        var http = new HttpClient();
        var json = await http.GetStringAsync(url);

        recipes = JsonConvert.DeserializeObject<List<Recipe>>(json);
        await UpdateCache(recipes);
      }
      else
      {
        recipes = await ReadCache();
      }

      return recipes;
    }

    private async static Task UpdateCache(IList<Recipe> recipes)
    {
      string fileName = "recipes.sqlite";

      var db = new SQLiteAsyncConnection(fileName, true);
      
      // create table (if it doesn't exist)
      await db.CreateTableAsync<Recipe>();

      // create table
      foreach (var item in await db.Table<Recipe>().ToListAsync())
      {
        await db.DeleteAsync(item);
      }

      // save recipes
      await db.InsertAllAsync(recipes);

      SQLiteConnectionPool.Shared.Reset();
    }

    private async static Task<IList<Recipe>> ReadCache()
    {
      string fileName = "recipes.sqlite";

      var db = new SQLiteAsyncConnection(fileName, true);
      
      var recipes = await db.Table<Recipe>().ToListAsync();
      SQLiteConnectionPool.Shared.Reset();

      return recipes;
    }

    public async static Task<RecipeDetail> GetRecipeDetail(int id)
    {
      var url = new Uri(string.Format("{0}/{1}", RECIPE_BASEURL, id));

      var http = new HttpClient();
      var json = await http.GetStringAsync(url);
      var recipe = JsonConvert.DeserializeObject<RecipeDetail>(json);
      return recipe;
    }
  }
}
